package com.fzq.flowable_demo.service;

import jakarta.servlet.http.HttpServletResponse;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.dmn.model.GraphicInfo;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.io.InputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProcessDiagramService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    /**
     * 生成流程图（支持运行中和已结束的流程）
     */
    public void generateDiagram(HttpServletResponse response, String processInstanceId) throws IOException {
        if (processInstanceId == null || processInstanceId.trim().isEmpty()) {
            throw new IllegalArgumentException("流程实例ID不能为空");
        }

        // 1. 先查询运行中的流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        String processDefinitionId;
        BpmnModel bpmnModel;
        List<String> activeActivityIds = Collections.emptyList();
        List<String> highLightedActivities;
        List<String> highLightedFlows = new ArrayList<>();

        if (processInstance != null) {
            // 流程正在运行中
            processDefinitionId = processInstance.getProcessDefinitionId();
            bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            activeActivityIds = runtimeService.getActiveActivityIds(processInstanceId);
            highLightedFlows = getHighlightedFlows(processInstanceId);
            // 获取历史活动节点
            List<HistoricActivityInstance> historicActivities = historyService
                    .createHistoricActivityInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();

            highLightedActivities = historicActivities.stream()
                    .map(HistoricActivityInstance::getActivityId)
                    .collect(Collectors.toList());

        } else {
            // 2. 如果运行中实例不存在，查询历史流程实例
            HistoricProcessInstance historicProcessInstance = historyService
                    .createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();

            if (historicProcessInstance == null) {
                throw new IllegalArgumentException("流程实例不存在，ID: " + processInstanceId);
            }

            processDefinitionId = historicProcessInstance.getProcessDefinitionId();
            bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
            highLightedFlows = getHighlightedFlows(processInstanceId);
            // 获取所有历史活动节点
            List<HistoricActivityInstance> historicActivities = historyService
                    .createHistoricActivityInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricActivityInstanceStartTime()
                    .asc()
                    .list();

            highLightedActivities = historicActivities.stream()
                    .map(HistoricActivityInstance::getActivityId)
                    .collect(Collectors.toList());
        }

        // 生成流程图
        ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();

        InputStream imageStream = diagramGenerator.generateDiagram(
                bpmnModel,
                "png",                    // imageType: 图片格式
                highLightedActivities,    // 高亮的活动节点
                highLightedFlows,  // 高亮的连线
                "宋体",                   // 活动字体
                "宋体",                   // 标签字体
                "宋体",                   // 注解字体
                null,                     // 类加载器
                1.0,                      // scaleFactor: 缩放因子
                true                      // drawSequenceFlowNameWithNoLabelID: 是否绘制连线名称
        );

        // 输出到响应
        response.setContentType("image/png");
        response.setHeader("Content-Disposition",
                "inline; filename=process-diagram-" + processInstanceId + ".png");

        IOUtils.copy(imageStream, response.getOutputStream());
        response.flushBuffer();
    }

    /**
     * 检查流程实例是否存在
     */
    public boolean isProcessInstanceExists(String processInstanceId) {
        if (processInstanceId == null || processInstanceId.trim().isEmpty()) {
            return false;
        }

        // 检查运行中实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        if (processInstance != null) {
            return true;
        }

        // 检查历史实例
        HistoricProcessInstance historicProcessInstance = historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        return historicProcessInstance != null;
    }

    /**
     * 获取流程实例状态信息
     */
    public String getProcessInstanceStatus(String processInstanceId) {
        if (processInstanceId == null || processInstanceId.trim().isEmpty()) {
            return "ID为空";
        }

        // 检查运行中实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        if (processInstance != null) {
            return "运行中";
        }

        // 检查历史实例
        HistoricProcessInstance historicProcessInstance = historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();

        if (historicProcessInstance != null) {
            if (historicProcessInstance.getEndTime() != null) {
                return "已结束";
            } else {
                return "未知状态";
            }
        }

        return "不存在";
    }


    /**
     * 获取高亮的连线ID列表
     */
    private List<String> getHighlightedFlows(String processInstanceId) {
        List<HistoricActivityInstance> historicActivities = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .activityType("sequenceFlow")  // 只查询连线类型的活动
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();

        return historicActivities.stream()
                .map(HistoricActivityInstance::getActivityId)
                .collect(Collectors.toList());
    }
}
